var express = require('express');
var router = express.Router();
const { adminModel } = require('../model/Model');
const { jiami } = require('../untils/crypto');
const { sign } = require('jsonwebtoken');
const { expressjwt } = require('express-jwt');
const upload = require('../public/js/uploadStorage');


//管理员登录
router.post('/login', async function (req, res) {
  let { username, password } = req.body;
  password = jiami(password);
  const user = await adminModel.findOne({ username, password });
  if (user) {
    res.json({
      flag: true,
      msg: '登录成功喽',
      token: sign({ level: user.level, username: user.username }, 'fish', { expiresIn: '2h' })
    })
  } else {
    res.json({
      flag: false,
      msg: '用户名或密码错误啦'
    })
  }
})
//以下页面均需密钥
router.all('*', expressjwt({ secret: 'fish', algorithms: ['HS256'] }), (req, res, next) => {
  next();
})
// 验证token
router.all('/token', function (req, res) {
  res.json({
    flag: true
  })
})
//验证超管注册权限
router.get('/regVerity', async function (req, res) {
  if (req.auth.level == 0) {
    res.json({
      flag: true,
      msg: 'welcome back superAdmin~'
    })
  } else {
    res.json({
      flag: false,
      msg: '没有权限哦'
    })
  }
})
//管理员注册用户名重名验证
router.get('/regUsername', async function (req, res) {
  const { username } = req.query;
  const user = await adminModel.findOne({ username });
  if (user) {
      res.json({
          flag: false,
          msg: '用户名已存在'
      })
  } else {
      res.json({
          flag: true,
          msg: '用户名可用'
      })
  }
})
//管理员注册
router.post('/reg', upload.single('avatar'), async function (req, res) {

  if (req.auth.level == 0) {
    let { username, password, level } = req.body;
    password = jiami(password);
    //拼接头像路径
    let path = req.file.destination + req.file.filename;
    path = path.slice(path.indexOf('/'));

    const user = await adminModel.findOne({ username });
    if (user) {
      res.json({
        flag: false,
        msg: '用户名已存在'
      })
    } else {
      const user = await adminModel.create({ avatar: path, username, password, level });
      if (user) {
        res.json({
          flag: true,
          msg: '注册成功啦'
        })
      } else {
        res.json({
          flag: false,
          msg: '数据库出错啦'
        })
      }

    }
  }

})
//获取管理员头像信息
router.get('/avatar', async function (req, res) {
  const user = await adminModel.findOne({ username: req.auth.username });
  if (user) {
    res.json({
      flag: true,
      data: user
    })
  } else {
    res.json({
      flag: false,
      msg: '数据库出错啦'
    })
  }
})

//修改管理员密码
router.post('/changePwd', async function (req, res) {
  let { oldPwd, newPwd } = req.body;
  oldPwd = jiami(oldPwd);
  newPwd = jiami(newPwd);
  const user = await adminModel.findOne({ username: req.auth.username, password: oldPwd });
  console.log(user);
  if (user) {
    await adminModel.findOneAndUpdate({ username: req.auth.username }, { password: newPwd }).then(result => {
      res.json({
        flag: true,
        msg: '密码修改成功'
      })
    })

  } else {
    res.json({
      flag: false,
      msg: '原始密码错误'
    })
  }
})
//获取管理员列表时判断超管权限
router.get('/verifySuperAdmin', async function (req, res) {
  console.log(req.auth.username);
  const user = await adminModel.findOne({ username: req.auth.username });
  if (user) {
    res.json({
      flag: true,
      data: user
    })
  } else {
    res.json({
      flag: false,
      msg: '数据库出错啦'
    })
  }
})
//获取管理员列表
router.get('/listAdmin', async function (req, res) {
  let { pageCurrent, pageSize } = req.query;
  //获取document总数
  let documentTotal = await adminModel.count();
  if (documentTotal) {
    adminModel.find()
      //掠过的document数量
      .skip((pageCurrent - 1) * pageSize)
      //每页显示的document数量
      .limit(pageSize)
      .then(list => {
        res.json({
          flag: true,
          data: list,
          pageTotal: Math.ceil(documentTotal / pageSize)
        })
      })
  } else {
    res.json({
      flag: false,
      msg: '数据库没有找到数据'
    })
  }
})

//删除管理员
router.get('/deleteAdmin', async function (req, res) {
  if (req.auth.level == 0) {
    const { username } = req.query;
    const user = await adminModel.findOneAndDelete({ username });
    if (user) {
      res.json({
        flag: true,
        msg: '删除成功啦'
      })
    } else {
      res.json({
        flag: false,
        msg: '删除失败'
      })
    }
  } else {
    res.json({
      flag: false,
      msg: '没有权限哦'
    })
  }
})
module.exports = router;